package com.biz.service.HService.user;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.biz.model.Hmodel.sys.TSysUser;
import com.biz.model.Hmodel.sys.Tmenu;
import com.biz.model.Hmodel.sys.TsystemLog;
import com.biz.model.Hmodel.sys.TuserRole;
import com.biz.model.Pmodel.sys.PsysRole;
import com.biz.model.Pmodel.sys.PsystemLog;
import com.biz.model.Pmodel.sys.Puser;
import com.biz.model.common.Pager;
import com.biz.service.HService.sys.BaseServiceImpl;
import com.biz.utils.MD5Util;
import com.biz.utils.StringUtil;
import com.biz.utils.URLConectionUtil;
import com.framework.dao.hdao.BaseDaoI;
import com.framework.dao.mdao.DaoSupport;
import com.framework.util.UuidUtil;

@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<TSysUser> implements UserServiceI {
	@Resource(name = "daoSupport")
	private DaoSupport dao;
	
	@Autowired
	private BaseDaoI<TSysUser> userdao;
	
	@Autowired
	private BaseDaoI<TuserRole> userRoleDao;
	
	@Autowired
	private BaseDaoI<Tmenu> menuDao; 
	
	@Autowired
	private BaseDaoI<TsystemLog> sysLogDao;
	
	@Override
	public List<Puser> findByPwd(Puser puser) throws Exception {
		if(puser!=null&&!StringUtil.isNullOrEmpty(puser.getPwd())){
			puser.setPwd(MD5Util.md5(puser.getPwd()));
		}
		return (List<Puser>)dao.findForList("userDao.findByPwd", puser);
	}
	
	@Override
	public Pager<PsystemLog> getSystemLog(Pager pager)
			throws Exception {
		return (Pager<PsystemLog>) dao.findForPager1("userDao.findLogPage", "userDao.logCount",pager);
		
	}

	@Override
	public Pager<Puser> findByType(Pager pager) throws Exception {
		Pager<Puser> pager_back=(Pager<Puser>)dao.findForPager1("userDao.findUserPage","userDao.countUser", pager);
		List<Puser> list_user=pager_back.getExhibitDatas();
		List<Puser> list_user1=getUserDetail(list_user);
		pager_back.setExhibitDatas(list_user1);
		return pager_back;
	}
	/**
	 * 获取用户详情html
	 * @param id
	 * @param storeId
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	private List<Puser> getUserDetail(List<Puser> list_user) throws Exception{
		String ids="";
		if(list_user != null && list_user.size() > 0)
		{
			for(Puser pu : list_user)
			{
				if(pu.getId() != null )
				{
					ids+= pu.getId()+",";
				}
			}	
		}
		String id = StringUtil.formatSqlIn(ids);
		
		if(!"".equals(id))
		{              
			List<Puser> list = (List<Puser>)dao.findForList("userDao.queryDetail",id);
			
			if(list_user != null && list_user.size() > 0 && list != null && list.size() > 0) {
				for(Puser pu : list_user)
				{
					String html = "";
					int flag = 0;
					String html1 = "";
					for(Puser puser : list)
					{
						if(puser.getId() != null && pu.getId()!= null && puser.getId().equals(pu.getId()))
						{
							if(flag == 0)
							{
								html+="<div class=\"wddd-list-jtzl\">"+
						            	"<ul>"+
						            	"<li style=\"width:20%\">注册/关注时间</li>"+
						            	"<li style=\"width:40%\">地址</li>"+
						            	"<li style=\"width:20%\">生日</li>"+
						            	"<li style=\"width:20%\">订单数</li>"+
						            "</ul>";
							}
							
							html+="<ul>"+
				                	"<li style=\"width:20%;padding:15px 0;\">"+puser.getRegisterTime()+"</li>";
							if(puser.getProvinceName()==null||puser.getProvinceName()==""){
								html+="<li style=\"width:40%;padding:15px 0;\">"+" "+"</li>";
							}else{
								html+="<li style=\"width:40%;padding:15px 0;\">"+puser.getProvinceName()+" "+puser.getCityName()+" "+puser.getAreaName()+"</li>";
							}if(puser.getBirthday()==null||puser.getBirthday()==""){
								html+="<li style=\"width:20%;padding:15px 0;\">"+" "+"</li>";
							}else{
								html+="<li style=\"width:20%;padding:15px 0;\">"+puser.getBirthday()+"</li>";
							}
							
							html+="<li style=\"width:20%;padding:15px 0;\">"+puser.getOrderCount()+"</li>"+
				                "</ul>";
							if(flag == 0)
							{
								html1+="<div class=\"clear\"></div>"+
								"</div>";
								flag++;
							}
						}
					}
					
					html += html1;
					/*html="<div class=\"wddd-list-jtzl\"><ul><li style=\"width:30%\">注册/关注时间</li><li style=\"width:50%\">地址</li></ul><ul><li style=\"width:30%;padding:15px 0;\">Thu Jun 02 17:39:04 CST 2016</li><li style=\"width:50%;padding:15px 0;\"></li></ul><div class=\"clear\"></div></div>";*/
					
					pu.setUserDetailHtml(html);
				}	
			}
		}
		
		return list_user;
	}

	@Override
	public List<PsysRole> findRole() throws Exception {
		return (List<PsysRole>) dao.findForList("userDao.findRole", null);
	}

	/**
	 * 根据登陆名查找用户信息
	 */
	@Override
	public boolean findbyLoginName(String loginName) throws Exception {
		Puser user=(Puser)dao.findForObject("userDao.findUserByLoginName", loginName);
		if(user!=null){
			return true;
		}
		return false;
	}

	@Override
	public void saveUser(Puser puser,Puser loginUser) throws Exception {
		puser.setPwd(MD5Util.md5("88888888"));
		puser.setId(UuidUtil.get32UUID());
//		puser.setCode(UuidUtil.getRndNumCode());
		//1.保存用户
		dao.save("userDao.saveNewUser",puser);
		//2.保存操作新增
		TsystemLog tSysLog = new TsystemLog();
		tSysLog.setDoUserId(loginUser.getId());
//		tSysLog.setMapId(loginUser.getMapId());					
		tSysLog.setState("10");
		tSysLog.setModifyInfo(loginUser.getPersonName()+"新增账号："+puser.getLoginName());
		sysLogDao.save(tSysLog);
	}
	
	@Override
	public boolean updateUser(Puser puser,Puser loginUser) throws Exception {
		//更新用户
		int i=(int) dao.update("userDao.updateUserinfo",puser);
		TsystemLog tSysLog = new TsystemLog();
		tSysLog.setDoUserId(loginUser.getId());
//		tSysLog.setMapId(loginUser.getMapId());					
		tSysLog.setState("11");
		tSysLog.setModifyInfo(loginUser.getPersonName()+"更新账号："+puser.getLoginName());
		sysLogDao.save(tSysLog);
		if(i>0)
			{return false;}
		else
			{return true;}
			
	}
	
	@Override
	public int deleteByIds(String ids,Puser loginUser) throws UnsupportedEncodingException {
		String[] idList1=ids.split(",");
		for(String id:idList1){
			String url = "http://wx.5d.com.cn:8081/bsi/toDelMallUser.action";
			Map<String, String> map = new HashMap<String, String>();
			map.put("id",id);
			String x = URLConectionUtil.httpURLConnectionPostDiy(url, map);
			x = URLDecoder.decode(x, "utf-8");
			Map<String, String> map1 = JSON.parseObject(x, Map.class);
			if(map1.get("flag").equals("fail")){
				return 1;
			}
		}
		String hql=StringUtil.formateString("update TSysUser set isdel=1 where id in({0})",StringUtil.formatSqlIn(ids));
		userdao.executeHql(hql);
		
		String[] idList=ids.split(",");
		for(String id :idList)
		{	TSysUser tSysUser=userdao.getById(TSysUser.class, id);
			TsystemLog tSysLog = new TsystemLog();
			tSysLog.setDoUserId(loginUser.getId());
//			tSysLog.setMapId(loginUser.getMapId());					
			tSysLog.setState("9");
			tSysLog.setModifyInfo(loginUser.getPersonName()+"删除账号："+tSysUser.getLoginName());
			sysLogDao.save(tSysLog);
		}
		return 0;
	}

	@Override
	public void updatePwdForChange(Puser puser) throws Exception {
		TSysUser sysUser=getById(puser.getId());
		sysUser.setPwd(puser.getPwd());
		update(sysUser);
		dao.update("userDao.updateUserMainPwdForChange", puser);
	}
	@Override
	public List<Puser> findExportExcel(Map<String,Object> map) throws Exception {
		return (List<Puser>)dao.findForList("userDao.findExportUser",map);
	}

	@Override
	public Puser getinfoById(String id) throws Exception {
		return (Puser) dao.findForObject("userDao.findinfoById",id);
		
	}

	@Override
	public List<Map<String, Object>> LoadLevel() throws Exception {
		List<Map<String, Object>> list=(List<Map<String, Object>>) dao.findForList("userDao.LoadLevel", null);
		return list;
	}
}
